/*
 *  Copyright (C) 2004 Cidero, Inc.
 *
 *  Permission is hereby granted to any person obtaining a copy of 
 *  this software to use, copy, modify, merge, publish, and distribute
 *  the software for any non-commercial purpose, subject to the
 *  following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
 *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY IN CONNECTION WITH THE SOFTWARE.
 * 
 *  File: $RCSfile: PlayQueue.java,v $
 *
 */

package com.cidero.bridge.audiotron;


import java.io.StringReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Logger;

/**
 *
 *  Audiotron play queue class.  The Audiotron maintains an internal
 *  play queue that holds a bunch of info for each song.  It is necessary
 *  to access the play queue to get the play queue index of the 
 *  turtle radio URL's  used to stream data to the audiotron from the
 *  UPnP bridge.  (Awkward Audiotron remote control API)
 *
 *  Below is an example of a play queue returned via an HTTP request.
 *  In the example, 2 turtle radio stations have been defined using
 *  the same 'friendlyName' ('LivingRoom'), allowing the living room
 *  Audiotron to be controlled by a UPnP bridge running on a host with
 *  either of the 2 IP addresses shown.  Note that if there was an 
 *  additional Audiotron in the home named 'Bedroom', there would be 2
 *  more turtle radio entries for that unit. 
 *
 *   [Play Queue]
 *   Start=0
 *   [Song 0]
 *   RandIndex=2
 *   Title=LivingRoomSourceIP100
 *   Artist=LivingRoomSourceIP100
 *   Genre=Home
 *   Track=-1
 *   Time=0
 *   CreateTime=135033
 *   ID=http://192.168.1.100:8081/Audiotron/LivingRoom
 *   [End Song 0]
 *   [Song 1]
 *   RandIndex=0
 *   Title=LivingRoomSourceIP10
 *   Artist=LivingRoomSourceIP10
 *   Genre=Home
 *   Track=-1
 *   Time=0
 *   CreateTime=135033
 *   ID=http://192.168.1.10:8081/Audiotron/LivingRoom
 *   [End Song 1]
 *   [Song 2]
 *   RandIndex=3
 *   Title=LivingRoomSourceIP11
 *   Artist=LivingRoomSourceIP11
 *   Genre=Home
 *   Track=-1
 *   Time=0
 *   CreateTime=135033
 *   ID=http://192.168.1.11:8081/Audiotron/LivingRoom
 *   [End Song 2]
 *   [End Play Queue]
 *
 *  The only fields of interest for this program are the [Play Queue],
 *  [Song], and ID fields. Other fields are just ignored for now.
 *
 */
public class PlayQueue 
{
  private static Logger logger = 
    Logger.getLogger("com.cidero.bridge.audiotron");

  Vector songList;
  boolean valid = false;

  public PlayQueue()
  {
    songList = new Vector();
  }
  
  /**
   *  Parse a play queue from the HTTP response string 
   */
  public boolean parse( String playQueue )
  {
    songList.clear();

    BufferedReader reader = 
      new BufferedReader( new StringReader( playQueue ) );
    
    try 
    {
      // First line should be '[Play Queue]'
      String line = reader.readLine();
      if( line == null || ! line.startsWith("[Play Queue") )
      {
        logger.warning("Play queue syntax error (doesn't start with [Play Queue]");
        return false;
      }
    
      Song currSong = null;
      int  songId = 0;

      while( (line = reader.readLine()) != null )
      {
        System.out.println("Line: " + line );
        
        if( line.startsWith("[Song") )
        {
          currSong = new Song( songId++ );
          songList.add( currSong );
        }
      
        if( line.startsWith("ID=") )
        {
          if( currSong != null )
          {
            currSong.id = line.substring(3);
          }
          else
          {
            logger.warning("Play queue syntax error (ID found before song)");
            return false;
          }
        }
      }
    }
    catch( IOException e )
    {
      logger.warning("Exception parsing play queue" + e );
      return false;
    }
    
    // set valid flag - only really need to parse Home radio station
    // category once for each program run (it shouldn't change)
    valid = true;
    
    return true;
  }

  public boolean isValid()
  {
    return valid;
  }

  public int getSongNumber( String uri )
  {
    for( int n = 0 ; n < songList.size() ; n++ )
    {
      Song song = (Song)songList.get(n);
      
      if( song.id.equals( uri ) )
        return song.songNumber;
    }

    logger.fine( "Couldn't find song in play queue with id '" + uri + "'" );
    
    return -1;
  }

  public class Song
  {
    int songNumber;
    String id;
    
    public Song( int songNumber )
    {
      this.songNumber = songNumber;
    }

    //public void setId( String id )
    //{
    //      this.id = id;
    //    }
  }
  
  /**
   * Simple test code
   */
  public static void main( String args[] )
  {
    StringBuffer buf = new StringBuffer();

    buf.append( "[Play Queue]\n" );
    buf.append( "Start=0\n" );    
    buf.append( "[Song 0]\n" );
    buf.append( "ID=http://192.168.1.100:8081/Audiotron/LivingRoom\n" );
    buf.append( "[End Song 0]\n" );
    buf.append( "[Song 1]\n" );
    buf.append( "ID=http://192.168.1.12:8081/Audiotron/LivingRoom\n" );
    buf.append( "[End Song 1]\n" );
    buf.append( "[End Play Queue]\n" );

    PlayQueue playQueue = new PlayQueue();
    
    playQueue.parse( buf.toString() );

    int songNum = playQueue.getSongNumber( "http://192.168.1.100:801/Audiotron/LivingRoom" );

    System.out.println("SongNum = " + songNum );
  }


}


